package com.dorm.cj.extension.restTemplate;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * 我们使用RestTemplate调用远程接口时，有时需要在header中传递信息，
 * 比如：traceId，source等，便于在查询日志时能够串联一次完整的请求链路，快速定位问题。
 */
public class TestRestTemplateInterceptor  implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        httpRequest.getHeaders().set("traceId", MdcUtil.get());
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }
}
